package cn.edu.nju.ws.sview.wyge.relations.adataset.entities.qxliu.algorithms;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.json.simple.JSONArray;

import cn.edu.nju.ws.sview.cache.URIIDCache;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.wyge.relations.datasets.DatasetItem;

public class ClassManager {
//	String ds_type = null;
//	Integer ds_id = -1;
	protected ArrayList<Integer> docid = null;
	HashMap<Integer, String[]> classMap = null;
	int size = -1;
	public ClassManager(ArrayList<Integer> docid){
		this.docid = docid;
	}

	public ClassManager(String ds_type, Integer ds_id) {
		this.getDocId(ds_id, ds_type);
//		this.ds_type = ds_type;
//		this.ds_id = ds_id;
	}

	public ClassManager(HashMap<Integer, String[]> classIdUriMap){
		this.classMap = classIdUriMap;
	}
	public Set<Integer> getClasses() {
		if (this.classMap == null) {
//			if (this.ds_type.contentEquals("custom")) {
//				this.getDocId();
				this.initClasses();
//			} else if (this.ds_type.contentEquals("uri")) {
//				this.docid = new ArrayList<Integer>();
//				docid.add(this.ds_id);
//				this.initClasses();
//			}
		}
		// System.out.println("classes:"+this.classMap.keySet());
		return this.classMap.keySet();
	}

	public HashMap<Integer, String[]> getNames() {
		if (this.classMap == null) {
//			if (this.ds_type.contentEquals("custom")) {
//				this.getDocId();
				this.initClasses();
//			} else if (this.ds_type.contentEquals("uri")) {
//				this.docid = new ArrayList<Integer>();
//				docid.add(this.ds_id);
//				this.initClasses();
//			}
		}
		return this.classMap;
	}
	/*
	 * get Document Ids of a data set
	 */
	public ArrayList<Integer> getDocId() {
		return this.docid;
	}
	private ArrayList<Integer> getDocId(int ds_id, String ds_type) {
		if(this.docid == null){
			if(ds_type.contentEquals(DatasetItem.URI_GENRE)){
				this.docid = new ArrayList<Integer>();
				docid.add(ds_id);
			}else if(ds_type.contentEquals(DatasetItem.CUSTOM_GENRE)){
				Connection conn = DBConnectionFactory.getConnection();
				try {
					PreparedStatement pstmt = conn
							.prepareStatement("select doc_id from custom_dataset_doc where dataset_id=?");
					pstmt.setInt(1, ds_id);
					ResultSet rs = pstmt.executeQuery();
					docid = new ArrayList<Integer>();
					while (rs.next()) {
						docid.add(rs.getInt(1));
					}
					rs.close();
					pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (conn != null) {
					try {
						conn.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
		}
		return this.docid;
	}
	/**
	 * get classes refered in the docs in docid
	 */
	private void initClasses() {
		Connection conn = DBConnectionFactory.getConnection();// .getFalconConnection();
		try {
			int docnum = docid.size();
			StringBuffer psql = new StringBuffer();
			for (int i = 0; i < docnum; i++) {
				psql.append("?,");
			}
			psql.replace(psql.lastIndexOf(","), psql.length(), ")");
			// PreparedStatement pstmt = conn
			// .prepareStatement("select o from quadruple where p=? and c in ("
			// + psql.toString());//
			// ("select o from quadruple where p=? and doc_id in ("+psql.toString());
			PreparedStatement pstmt = conn
					.prepareStatement("select o from quadruple where p=? and s like 'u%' and doc_id in ("
							+ psql.toString());
			int typeid = 0;
			try {
				typeid = URIIDCache.getInstance().getURIID(
						"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",//rdf:type
						false);
			} catch (Throwable e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			pstmt.setString(1, "u" + typeid);// rdf:type
			for (int i = 0; i < docnum; i++) {
				pstmt.setInt(i + 2, docid.get(i));
			}
			ResultSet rs = pstmt.executeQuery();
			classMap = new HashMap<Integer, String[]>();
			while (rs.next()) {
				String o = rs.getString(1);
				if (o.startsWith("u"))
					o = o.substring(1);// e.g. "u29623577"-->"29623577"
				Integer oid = Integer.valueOf(o);
				if (!classMap.containsKey(oid)) {
					classMap.put(oid, this.getItem(oid));
				}
			}
			rs.close();
			pstmt.close();
			this.size = this.classMap.size();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private String[] getItem(int id) {
		String localname = null;
		String uri = null;
		try {
			Connection conn = DBConnectionFactory.getConnection();// .getFalconConnection();
			PreparedStatement pstmt = conn
					.prepareStatement("select uri from uri where id=?");
			pstmt.setInt(1, id);
			ResultSet rs = pstmt.executeQuery();
			if (rs.next()) {
				uri = rs.getString(1);
			}
			rs.close();
			pstmt.close();
			conn.close();
			int idx = uri.lastIndexOf("#");
			if (idx == -1) {
				idx = uri.lastIndexOf("/");
			}
			if (idx == uri.length() - 1) {
				localname = uri;
			} else {
				localname = uri.substring(idx + 1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// System.out.println(localname);
		String[] item = { uri, localname };
		return item;
	}

}
